<template>
  <div>
    <div @click="fullClick">源代码</div>
    <div ref="editor" class="editor" style="text-align:left;margin: 5px;width: 700px" />

    <!--全屏模式-->
    <div ref="fullEditor" class="cover">
      <el-input type="textarea" :rows="30" v-model="desc" style="width:100%" />
      <el-button @click="save">保存</el-button>
      <el-button @click="close">关闭</el-button>
    </div>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import E from 'wangeditor'
import { getToken } from '@/utils/auth'
export default {
  name: 'Editor',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      headers: {
        'Authorization': getToken()
      },
      info: null,
      editor: null,
      desc: ''
    }
  },
  computed: {
    ...mapGetters([
      'uploadApi'
    ])
  },
  watch: {
    value: function(val) {
      this.editor.txt.html(val)
      // this.editor.txt.html(val)
    }
  },
  methods: {
    fullClick() {
      const fullEditor = this.$refs.fullEditor
      console.log('fullEditor====>', this.editor.txt.html())
      fullEditor.style.display = 'block'
      this.desc = this.editor.txt.html()
    },
    save() {
      console.log('save=====>', this.desc)
      this.editor.txt.html(this.desc)
    },
    close() {
      const fullEditor = this.$refs.fullEditor
      fullEditor.style.display = 'none'
    }
  },
  mounted() {
    // console.log(222)
    console.log(this.value)
    this.editor = new E(this.$refs.editor)
    this.editor.customConfig.uploadImgShowBase64 = true // 使用 base64 保存图片
    // 不可修改
    this.editor.customConfig.uploadImgHeaders = this.headers
    // 自定义文件名，不可修改，修改后会上传失败
    this.editor.customConfig.uploadFileName = 'file'
    this.editor.customConfig.uploadImgServer = this.uploadApi // 上传图片到服务器
    this.editor.customConfig.uploadImgMaxLength = 5
    this.editor.customConfig.uploadImgHooks = {
      customInsert: function(insertImg, result, editor) {
        var url = result.link
        // insertImg(url)
        console.log('this.editor', editor)
        editor.cmd.do('insertHtml', '<img src="' + url + '" style="display:flex; max-width:100%;"/>')
      }
    }
    this.editor.customConfig.onchange = (html) => {
      this.info = html
      this.$emit('change', this.info)
      this.$emit('input', this.info)
    }
    this.editor.create()
    this.editor.txt.html(this.value)
  }
}
</script>

<style scoped>
  .editor-content{
    padding-left: 5px;
  }
  .editor{
    background-color: white;
    height: 100%;
  }
  .cover{
    display: none;
    position: fixed;
    z-index: 999900000;
    top: 50px;
    left: 50px;
    right: 50px;
    height: 90%;
    padding: 20px;
    background-color: #f1f1f1;
  }
</style>
